package be.ipl.streams.servlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collection;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.streams.domaine.Game;
import be.ipl.streams.domaine.Player;
import be.ipl.streams.exceptions.ArgumentInvalideException;
import be.ipl.streams.exceptions.GameStartedException;
import be.ipl.streams.usecases.GameManagement;
import be.ipl.streams.util.Util;


@WebServlet("/lobby.html")
public class Lobby extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private GameManagement gameManagement;
	
	@Override
	protected void doPost (HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Player player = (Player) Controleur.testConnected(this, request, response);
		if (player == null) return;
		
		Game game = (Game) request.getSession().getAttribute("game");
		if (game != null) {
			doGet(request, response);
			return;
		}
		
		int idPartie = Integer.parseInt(request.getParameter("gameID"));
		
		try {
			game = gameManagement.join(idPartie, player);
			request.getSession().setAttribute("game", game);
			
			doGet(request, response);
		} catch (GameStartedException e) {
			request.setAttribute("message",
					"La partie a deja commencee");
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"parties");
			rd.forward(request, response);
		} catch (ArgumentInvalideException e) {
			request.setAttribute("message",
					"une erreur est survenue, la partie est nulle");
			RequestDispatcher rd = getServletContext().getNamedDispatcher(
					"parties");
			rd.forward(request, response);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Player player = (Player) Controleur.testConnected(this, request, response);
		if (player == null) return;
		Game game = (Game) Controleur.testGameJoined(this, request, response);
		if (game == null) return;
		
		request.setAttribute("timeout", Math.max(1, 1 +
				(game.getStartTime().getTime().getTime()
				- Calendar.getInstance().getTime().getTime()) / 1000 +
				Util.DELAI_START_GAME) + "; URL=partie.html");
		Collection<Player> players = gameManagement.listPlayers(game);
		request.getSession().setAttribute("players", players);
		
		RequestDispatcher rd = getServletContext().getNamedDispatcher("lobby");
		rd.forward(request, response);
	}
	
}
